import cv2

from flask import Flask, request, jsonify
from wired_table_rec import WiredTableRecognition
from rapidocr_onnxruntime import  RapidOCR

app = Flask(__name__)


@app.route('/ocr' , methods=['POST'])
def rec():  # 文字识别
    engine = RapidOCR()
    path = request.json['path'] #接收入参
    result, elapse = engine(path)
    result_string = ''
    for results in result:
        result_string = result_string + results[1] + "\n"
    print(result_string)
    return result_string


@app.route('/table_ocr' , methods=['POST'])
def table_ocr(): # 单表格识别
    # image = cv2.imread('D:/opencv/sacn/picture-0.jpg')
    # image = cv2.imread('D:/opencv/image/table-12.png')
    path = request.json['path']
    table = opencv(path)

    # image = cv2.imread('table.png')

    image = cv2.resize(table, (1450, 1056))  # 设置图片分辨率为1450*1056(分辨率低于1500识别率最高)
    table_rec = WiredTableRecognition()
    html, elasp, polygons, logic_points, ocr_res = table_rec(image)
    return html

@app.route('/table_list_ocr' ,  methods=['POST'])
def table_lis_ocr(): # 多表格识别
    # image = cv2.imread('D:/opencv/sacn/picture-0.jpg')
    # image = cv2.imread('D:/opencv/image/table-12.png')
    path = request.json['path']
    tables = opencvTables(path)

    # image = cv2.imread('table.png')
    result = []
    for table in tables:
        image = cv2.resize(table, (1450, 1056))  # 设置图片分辨率为1450*1056(分辨率低于1500识别率最高)
        table_rec = WiredTableRecognition()
        html, elasp, polygons, logic_points, ocr_res = table_rec(image)
        result.append(html)
    return jsonify(result)


def opencv(str): # 单表格识别
    # 读取图片
    # image = cv2.imread('D:/table-0.jpg')

    image = cv2.imread(str)

    # 转灰度
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 应用高斯模糊
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 阈值化处理
    _, thresh = cv2.threshold(blurred, 150, 255, cv2.THRESH_BINARY_INV)

    # 寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    table_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 1000]
    max_contour = max(table_contours, key=cv2.contourArea)
    # 获取轮廓的边界框
    x, y, w, h = cv2.boundingRect(max_contour)

    # 根据边界框截取表格
    table = image[y:y + h, x:x + w]
    return table


def opencvTables(str): # 多表格识别
    # 读取图片
    # image = cv2.imread('D:/table-0.jpg')

    # 读取图片
    image = cv2.imread(str)
    # 转灰度
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 应用高斯模糊
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 阈值化处理
    _, thresh = cv2.threshold(blurred, 150, 255, cv2.THRESH_BINARY_INV)

    # 寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    tables = []
    for contour in contours:
        # 近似轮廓
        approx = cv2.approxPolyDP(contour, 5, True)
        #
        # # 检查是否接近矩形
        if len(approx) == 4:
           are = cv2.contourArea(contour)
           if are < 10000: continue
           cv2.drawContours(image, [approx], 0, (0, 255, 0), 3)

           # 获取矩形的坐标
           x, y, w, h = cv2.boundingRect(approx)

           # 裁剪表格
           table = image[y:y + h, x:x + w]
           tables.append(table)

    # 保存结果（如果需要）
    # for i, table in enumerate(tables):
    #     cv2.imwrite(f'table_{i + 1}.jpg', table)
    return tables




# @app.route("/test" ,  methods=['POST'])
@app.route("/test")
def test():
    # path = request.json['path']
    return 'path'


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
